package com.example.bookkeepingelf.business.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.bookkeepingelf.R;
import com.example.bookkeepingelf.base.utils.StringUtils;
import com.example.bookkeepingelf.base.utils.ToastUtils;
import com.example.bookkeepingelf.business.constant.AccountBookConstant;
import com.example.bookkeepingelf.business.database.dialog.CustomDatePickerDialog;
import com.example.bookkeepingelf.business.database.service.CalculatorService;
import com.example.bookkeepingelf.business.database.service.impl.CalculatorServiceImpl;
import com.google.android.material.datepicker.MaterialDatePicker;

import java.math.BigDecimal;
import java.util.Calendar;

import cn.hutool.core.lang.func.VoidFunc0;

public class AccountingActivity extends AppCompatActivity {

    private CalculatorService calculatorService;

    private TextView textView;
    private Button butNumber0;
    private Button butNumber1;
    private Button butNumber2;
    private Button butNumber3;
    private Button butNumber4;
    private Button butNumber5;
    private Button butNumber6;
    private Button butNumber7;
    private Button butNumber8;
    private Button butNumber9;
    private ImageButton butMiniDrop;
    private ImageButton butDelete;
    private ImageButton butAdd;
    private ImageButton butSubtract;
    private ImageButton butMultiply;
    private ImageButton butDivision;
    private ImageButton butBack;

    private LinearLayout butSelectDate;

    /**
     * 0: 取消
     * 1: 等于
     * 2: 完成
     */
    private int backStatus = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_accounting);
        this.calculatorService = new CalculatorServiceImpl();
        // 初始化数字按钮
        this.initView();
        // 添加按钮点击事件
        this.addButClickListener();


    }

    private Handler handler = new Handler();
    private boolean isDeleting = false; // 标记是否正在删除
    private static final long DELETE_INTERVAL = 150; // 删除间隔时间（毫秒）

    // 定时删除任务
    private Runnable deleteTask = new Runnable() {
        @Override
        public void run() {
            if (!isDeleting) {
                return; // 如果已经停止删除，则退出
            }
            String currentText = calculatorService.removeOne(textView);
            textView.setText(currentText);
            calculateChangeBackBut(currentText);
            if (AccountBookConstant.ZERO_STR.equals(currentText)) {
                isDeleting = false;
                stopDeleting();
            }
            // 继续下一次删除
            if (isDeleting) {
                handler.postDelayed(this, DELETE_INTERVAL);
            }
        }
    };

    @SuppressLint("ClickableViewAccessibility")
    private void addButClickListener() {
        this.setButOnClickListener(this.butNumber0, R.id.jsq_number_0);
        this.setButOnClickListener(this.butNumber1, R.id.jsq_number_1);
        this.setButOnClickListener(this.butNumber2, R.id.jsq_number_2);
        this.setButOnClickListener(this.butNumber3, R.id.jsq_number_3);
        this.setButOnClickListener(this.butNumber4, R.id.jsq_number_4);
        this.setButOnClickListener(this.butNumber5, R.id.jsq_number_5);
        this.setButOnClickListener(this.butNumber6, R.id.jsq_number_6);
        this.setButOnClickListener(this.butNumber7, R.id.jsq_number_7);
        this.setButOnClickListener(this.butNumber8, R.id.jsq_number_8);
        this.setButOnClickListener(this.butNumber9, R.id.jsq_number_9);
        this.setButOnClickListener(this.butMiniDrop, R.id.jsq_mini_drop);
        this.setButOnClickListener(this.butAdd, R.id.jsq_operate_add);
        this.setButOnClickListener(this.butSubtract, R.id.jsq_operate_subtract);
        this.setButOnClickListener(this.butMultiply, R.id.jsq_operate_multiply);
        this.setButOnClickListener(this.butDivision, R.id.jsq_operate_division);


        // 删除按钮长按事件
        // 长按事件
        this.butDelete.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                isDeleting = true; // 开始删除
                startDeleting();
                return true; // 表示事件已处理
            }
        });

        // 触摸事件监听器，用于检测用户松开按钮
        this.butDelete.setOnTouchListener((v, event) -> {
            if (!isDeleting) {
                return false; // 如果没有在删除中，直接返回
            }

            switch (event.getAction()) {
                case android.view.MotionEvent.ACTION_UP:
                case android.view.MotionEvent.ACTION_CANCEL:
                    isDeleting = false; // 停止删除
                    stopDeleting();
                    break;
            }
            return false;
        });

        //删除按钮点击事件
        this.butDelete.setOnClickListener(v1 -> {
            String str = calculatorService.removeOne(textView);
            textView.setText(str);
            calculateChangeBackBut(str);
        });


        //返回按钮点击事件
        this.butBack.setOnClickListener(v1 -> {
            switch (backStatus) {
                case 0:
                    //返回
                    finish();
                    break;
                case 1:
                    //等于
                    String str = calculatorService.convertTextResult(textView, R.id.jsq_operate_back);
                    if (StringUtils.isBlank(str)) {
                        return;
                    }
                    textView.setText(str);
                    this.calculateChangeBackBut(str);
                    break;
                case 2:
                    //完成
                    onOk();

                    break;
            }
        });

        this.butSelectDate.setOnClickListener( v1 -> {
            showDatePicker();
        });
    }

    private void showDatePicker() {
        // 创建 MaterialDatePicker
        MaterialDatePicker<Long> materialDatePicker = MaterialDatePicker.Builder.datePicker()
                .setTitleText("选择日期")
                .setTheme(R.style.CustomMaterialDatePickerTheme)
                .build();

        // 显示日期选择器
        materialDatePicker.show(getSupportFragmentManager(), "DATE_PICKER");

        // 监听用户选择的日期
        materialDatePicker.addOnPositiveButtonClickListener(selection -> {
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(selection);
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH) + 1; // 月份从0开始
            int day = calendar.get(Calendar.DAY_OF_MONTH);

            String selectedDate = year + "-" + month + "-" + day;
//            tvSelectedDate.setText("选中的日期: " + selectedDate);
        });
    }

    private void onOk() {
        String stringValue = calculatorService.getStringValue(this.textView);
        try {
            BigDecimal bigDecimal = new BigDecimal(stringValue);
            bigDecimal = bigDecimal == null ? BigDecimal.ZERO : bigDecimal;
            if (bigDecimal.compareTo(BigDecimal.ZERO) == 0) {
                ToastUtils.showCustomToast(this, this.butBack, "请输入有效金额");
                return;
            }
            // 保存到数据库


        }catch (NumberFormatException nfe){
            ToastUtils.showCustomToast(this, this.butBack, "请输入有效金额");
        }


    }


    // 开始删除
    private void startDeleting() {
        handler.post(deleteTask);
    }

    // 停止删除
    private void stopDeleting() {
        handler.removeCallbacks(deleteTask);
    }


    private void setButOnClickListener(View button, int id) {
        button.setOnClickListener(v1 -> {
            String str = calculatorService.convertTextResult(textView, id);
            if (StringUtils.isBlank(str)) {
                return;
            }
            textView.setText(str);
            this.calculateChangeBackBut(str);
        });
    }

    private void setButOnClickListener(View button, int id, Runnable task) {
        button.setOnClickListener(v1 -> {
            String str = calculatorService.convertTextResult(textView, id);
            if (StringUtils.isBlank(str)) {
                return;
            }
            textView.setText(str);

            task.run();
        });
    }



    private void calculateChangeBackBut(String text){
        if (StringUtils.isBlank(text)) {
            return;
        }
        //是否包含运算符
        if (calculatorService.isHaveOperator(text)) {

            //操作符是否在最后
            if (calculatorService.lastHaveOperator(text)) {
                backStatus = 0;
            }else {
                //等号是否在最后
                if (calculatorService.lastHaveMiniDrop(text)) {
                    backStatus = 0;
                }else {
                    //可以切换等号
                    backStatus = 1;
                }
            }
        }else {
            //不包含说明是数字和小数点
            //判断最后一位是否是小数点
            if (calculatorService.lastHaveMiniDrop(text)) {
                backStatus = 0;
            }else {
                //判断是否是0
                if (new BigDecimal(text).compareTo(BigDecimal.ZERO) == 0) {
                    backStatus = 0;
                }else {
                    backStatus = 2;
                }
            }
        }

        changeBackBut(backStatus);
    }

    private void changeBackBut(int status) {
        switch (status){
            case 0:
                this.butBack.setImageResource(R.drawable.jsq_back);
                break;
            case 1:
                this.butBack.setImageResource(R.drawable.jsq_eq);
                break;
            case 2:
                this.butBack.setImageResource(R.drawable.jsq_ok);
                break;
        }

    }


    private void initView() {
        this.textView = findViewById(R.id.jsq_result);
        this.butDelete = findViewById(R.id.jsq_operate_delete);
        this.butAdd = findViewById(R.id.jsq_operate_add);
        this.butSubtract = findViewById(R.id.jsq_operate_subtract);
        this.butMultiply = findViewById(R.id.jsq_operate_multiply);
        this.butDivision = findViewById(R.id.jsq_operate_division);
        this.butMiniDrop = findViewById(R.id.jsq_mini_drop);

        this.butBack = findViewById(R.id.jsq_operate_back);
        this.butSelectDate = findViewById(R.id.jsq_select_date_but);

        this.butNumber0 = findViewById(R.id.jsq_number_0);
        this.butNumber1 = findViewById(R.id.jsq_number_1);
        this.butNumber2 = findViewById(R.id.jsq_number_2);
        this.butNumber3 = findViewById(R.id.jsq_number_3);
        this.butNumber4 = findViewById(R.id.jsq_number_4);
        this.butNumber5 = findViewById(R.id.jsq_number_5);
        this.butNumber6 = findViewById(R.id.jsq_number_6);
        this.butNumber7 = findViewById(R.id.jsq_number_7);
        this.butNumber8 = findViewById(R.id.jsq_number_8);
        this.butNumber9 = findViewById(R.id.jsq_number_9);
    }
}